package com.zan.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zan.entity.ShoppingCart;
import com.zan.entity.Users;
import com.zan.service.ShoppingCartService;
import com.zan.vo.ResStatus;
import com.zan.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/shopcart")
@Api(value = "提供购物车业务相关接口", tags = "购物车管理")
public class ShopCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("/list")
    @ApiOperation("查询购物车列表接口")
    @ApiImplicitParam(dataType = "Integer", name = "userId", value = "用户ID", required = true)
    public ResultVo listShoppingCartByUserId(Integer userId, @RequestHeader("token") String token) {
        if (userId != null) {
            return shoppingCartService.listShoppingCartByUserId(userId);
        }
        return new ResultVo(ResStatus.NO.code, "fail", null);
    }

    @PostMapping("/add")
    @ApiOperation("添加购物车接口")
    public ResultVo addShoppingCart(@RequestBody ShoppingCart cart, @RequestHeader("token") String token) throws JsonProcessingException {
        //以购物车业务为例：假如需要用户信息
        String s = stringRedisTemplate.boundValueOps(token).get();
        Users users = objectMapper.readValue(s, Users.class);
        System.out.println(users);

        return shoppingCartService.addShoppingCart(cart);
    }

    @PutMapping("/update/{cid}/{cNum}")
    @ApiOperation("修改购物车数量接口")
    public ResultVo updateNum(@PathVariable("cid") Integer cartId,
                              @PathVariable("cNum") Integer cartNum,
                              @RequestHeader("token") String token) {
        return shoppingCartService.updateCartNum(cartId, cartNum);
    }

    @GetMapping("/listByCids")
    @ApiOperation("查询选中购物车列表接口")
    @ApiImplicitParam(dataType = "String", name = "cids", value = "选择的购物车记录id", required = true)
    public ResultVo listByCids(String cids, @RequestHeader("token") String token) {
        return shoppingCartService.listShoppingCartBycIds(cids);
    }
}
